<?php

namespace App\Admin\Services;

use App\Models\AdminUser;

class AuthService
{
    /**
     * @param $data
     * @return mixed
     */
    public function auth($data)
    {
        return AdminUser::where([
            'server_id' => $data['server_id'],
            'password'  => $data['password'],
        ])
            ->first();
    }

    public function register($data)
    {
        $data['password'] = bcrypt($data['password']);
        return AdminUser::create($data);
    }

    public function update($id, $update)
    {
        return AdminUser::find($id)->update($update);
    }

    /**
     * 通過id獲取客服，id為空返回所有
     * @param $id
     * @return mixed
     */
    public function users($keyword = '', $limit = 15)
    {
        $paginate = AdminUser::when($keyword, function ($query, $keyword) {
            $query->when(preg_match('/^\d{5}$/', $keyword), function ($query) use ($keyword) {
                $query->where('staff_id', $keyword);
            }, function ($query) use ($keyword) {
                $query->where('name', 'like', "%{$keyword}%");
                $query->orWhere('nickname', 'like', "%{$keyword}%");
            });
        })
            ->paginate($limit);

        $paginate->getCollection()->each(function ($item) {
            $item->setAppends(['enable_name', 'role_names']);
        });

        return $paginate;
    }

    public function user($id = 0)
    {
        return AdminUser::find($id);
    }

    /**
     * 根據id刪除用戶
     */
    public function deleteUsers($id)
    {
        return AdminUser::destroy((array)$id);
    }
}
